package com.dwaynema.config;

import com.dwaynema.dto.UserDto;
import com.dwaynema.entity.SysUser;
import com.dwaynema.jwt.JwtToken;
import com.dwaynema.service.UserService;
import com.dwaynema.util.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
    //权限控制
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Autowired
    TokenUtil tokenUtil;
    //用户控制
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken=(JwtToken)token;
        String username = tokenUtil.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        SysUser sysUser=userService.userLoginByUsername(String.valueOf(username));
        if(sysUser==null){
            throw new UnknownAccountException("账户不存在");
        }
        UserDto userDto=new UserDto();
        BeanUtils.copyProperties(sysUser,userDto);


        return new SimpleAuthenticationInfo(userDto,jwtToken.getCredentials(),getName());
    }
}
